package com.chb.test.redPacketDemo_10;

import java.util.Random;

public class People extends Thread{
    public People() {
    }

    public People(String name) {
        super(name);
    }
    int getRadPacket = 0; // 局部数据
    @Override
    public void run() {
        while (true) {
            synchronized (redPacket.look) {
                if(getRadPacket == 1) {
                    try {
                        redPacket.look.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                } else {
                    getRadPacket = 1;
                    if(redPacket.peopleNum == 0) {
                        break;
                    } else {
                        redPacket.peopleNum --;
                        if(redPacket.redPacketNum == 0) {
                            System.out.println(getName() + "没有抢到红包");
                        } else {
                            redPacket.redPacketNum --;
                            if(redPacket.redPacketNum == 0) {
                                System.out.println(getName() + "抢到了" + redPacket.price + "元红包");
                            } else {
                                Random random = new Random();
                                int randomPrice = random.nextInt(redPacket.price);
                                redPacket.price -= randomPrice;
                                System.out.println(getName() + "抢到了" + randomPrice + "元红包");
                            }
                        }
                    }
                    redPacket.look.notifyAll();
                }
                break;
            }
        }
    }
}
